package com.biz.service.api;

import com.alibaba.fastjson.JSON;
import com.biz.model.Pmodel.api.BaseUser;
import com.biz.model.Pmodel.api.activity.Pactivity;
import com.biz.model.Pmodel.api.activity.PfirstBalance;
import com.biz.model.Pmodel.weixin.UserInfo;
import com.biz.service.base.BaseServiceImpl;
import com.framework.dao.mdao.DaoSupport;
import com.framework.utils.ConfigUtil;
import com.framework.utils.MathUtil;
import com.framework.utils.URLConectionUtil;
import com.framework.utils.UuidUtil;
import com.framework.utils.weixin.WechatAccessToken;
import net.sf.json.JSONObject;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.text.SimpleDateFormat;
import java.util.*;

@Service("wxActivityService")
public class WxActivityServiceImpl extends BaseServiceImpl<Object> implements
        WxActivityServiceI {

    @SuppressWarnings("rawtypes")
    @Resource(name = "daoSupport")
    private DaoSupport dao;

    @Resource(name = "wxTemplateService")
    private WxTemplateServiceI wxTemplateService;

    @Resource(name = "wxUtilService")
    private WxUtilServiceI wxUtilService;


    /****************************开始: 所有活动方法******************************************/

    /**
     * 满足当前的活动
     *
     * @param type 1:只查询"关注送活动"
     * @return
     * @throws Exception
     */
    private List<Pactivity> ActivityListDate(int type) throws Exception {
        List<Pactivity> activity = new ArrayList<Pactivity>();
        SimpleDateFormat df = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");//设置日期格式
        Map<String, Object> selectmap = new HashMap<>();
        selectmap.put("type", type);
        selectmap.put("nowTime", df.format(new Date()));
        if (type == 1) {
            //关注送活动
            activity = (List<Pactivity>) dao.findForList("WxActivityDao.ActivityList", selectmap);
        }

        return activity;


    }

    /**
     * ***********************首次关注加券点********************************
     *
     * @param openid
     * @return
     */
    @Override
    public boolean adActivityListDate(String openid) throws Exception {
        boolean pd = false;
        if (isnull(openid)) {
            boolean user_bool= this.getselectUsermsgOpen_id(openid);
            if(user_bool){
                //读取用户信息，或新增用户
                BaseUser y_user= adduser(openid);

                String mapidList="";//获取所有mapid，一次性查出所有规则已改加的积分数
                List<String> tmplist=new ArrayList<String>();
                //查询满足的活动
                List<Pactivity> Pactivity= ActivityListDate(1);
                for(Pactivity ac_tmp:Pactivity){
                    tmplist.add(ac_tmp.getMapid());
                }

                if(tmplist.size()>0){
                    //获取需要加的规则
                    mapidList=ListToString_Quotes(tmplist);
                    Map<String,Object> mapidListdate=new HashMap<>();
                    mapidListdate.put("mapidList",mapidList);
                    List<PfirstBalance> firstBalance_tmp=(List<PfirstBalance>)dao.findForList("WxActivityDao.getfirstBalanceMapList",mapidListdate);
                    int add_balance_90=0;
                    for(PfirstBalance first:firstBalance_tmp){
                        //增加积分
                        if(y_user!=null){
                            //发券
                            JSONObject jSONObject_q = new JSONObject();
                            jSONObject_q.put("brand_code","");
                            jSONObject_q.put("shop_code", "");
                            jSONObject_q.put("user_code", "");
                            jSONObject_q.put("order_code", first.getId());
                            jSONObject_q.put("open_id", y_user.getOpen_id());
                            jSONObject_q.put("type", "2");
                            jSONObject_q.put("source", "6");
                            jSONObject_q.put("source_msg", "首次关注发券");
                            jSONObject_q.put("balance_90", first.getBalance_90());
                            jSONObject_q.put("state", 2);
                            jSONObject_q.put("commission", "0");
                            jSONObject_q.put("tradeType", "");
                            jSONObject_q.put("orderState", "1");
                            jSONObject_q.put("orderTotal", "0");
                            pd = user_Balance90(jSONObject_q);
                            add_balance_90+=first.getBalance_90();
                        }
                    }
                    try{
                        if(add_balance_90>0){
                            wxTemplateService.send_kf_template(openid, "首次关注获得"+ (add_balance_90/100)+"久零券");
                        }

                    }catch (Exception e){

                    }

                }else{
                    pd=true;//无满足条件
                }
            }else{
                pd=true;//不需要送
            }
        }
        return pd;
    }



    /**
     * 发券
     *
     * @return
     */
    private boolean user_Balance90(JSONObject jSONObject1) {
        Map<String, String> hash1 = new HashMap<String, String>();
        hash1.put("json", jSONObject1.toString());
        Map<String, Object> r_Interface = APIInterface(hash1, "api/balance/operUserBalance90.ac");
        if (r_Interface != null) {

            if ("0".equals(r_Interface.get("flag").toString()) || "3".equals(r_Interface.get("flag").toString()) ) {
                return true;
            } else {
                return false;
            }
        } else {
            return false;
        }
    }

    //接口
    public Map<String, Object> APIInterface(Map<String, String> jSONObject, String url) {
        Map<String, Object> map2 = new HashMap<String, Object>();
        try {
            String requestUrl = ConfigUtil.get("QT_Url") + url;
            String x = URLConectionUtil.httpURLConnectionPostDiy(requestUrl, jSONObject);
            x = URLDecoder.decode(x, "utf-8");
            if (x == null || x.trim().equals("") || x.trim().equals("失败")) {
                // 失败
            } else {
                map2 = JSON.parseObject(x, Map.class);
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } finally {
            return map2;
        }
    }

    /**
     * 空:false 不空:true
     *
     * @param s
     * @return
     */
    private boolean isnull(String s) {
        if (s == null || s.isEmpty()) {
            return false;
        } else {
            return true;
        }
    }

    //读取用户信息，如果没注册，则自动注册
    private BaseUser adduser(String open_id) throws Exception {
        UserInfo userinfo_new=new UserInfo();
        String Nickname="",Headimgurl="";
        int Sex=0;
        try{
            String accessToken= wxUtilService.getAccessToken();
            userinfo_new= WechatAccessToken.getUserInfo(accessToken,open_id);
            if(userinfo_new!=null){
                Nickname=userinfo_new.getNickname();
                Sex=userinfo_new.getSex();
                Headimgurl=userinfo_new.getHeadimgurl();
            }
        }catch (Exception e){

        }


        String userId = UuidUtil.get32UUID();
        BaseUser saveuser = new BaseUser();
        saveuser.setId(userId);
        saveuser.setOpen_id(open_id);
        saveuser.setPerson_name(Nickname);//用户昵称
        saveuser.setSex(Sex);//值为1时是男性，值为2时是女性，值为0时是未知
        saveuser.setCover(Headimgurl);//用户头像
        int i = (Integer) dao.save("WxtsDao.insertUser", saveuser);
        if (i > 0) {
            return saveuser;
        } else {
            return null;

        }
    }


    /**
     * *************************结束: 所有活动方法*****************************************
     */

    public boolean getselectUsermsgOpen_id(String open_id) throws Exception {
        Map<String, Object> select_map = new HashMap<>();
        select_map.put("open_id", open_id);
        return (Integer) dao.findForObject("WxActivityDao.selectUsermsgCount", select_map)==0;
    }


    /**
     * List<String> 转 String 逗号分隔（字段加引号）
     * @param listString
     * @return
     */
    public static String ListToString_Quotes(List<String> listString)
    {
        String rString="";
        for(String tmp:listString)
        {
            rString+="'"+tmp.trim()+"',";
        }

        if(rString.length()>0)
        {
            rString=rString.substring(0,rString.length()-1);
        }

        return  rString;
    }

}
